package com.lst.tools.custom.context;


import com.lst.tools.custom.constants.TokenConstants;

import java.util.HashMap;
import java.util.Map;


/**
 * 平台上下文线程副本管理类
 *
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
public class BaseContextHandler {
    /**
     * 线程副本
     */
    public static ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<Map<String, Object>>();

    public static void set(String key, Object value) {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            THREAD_LOCAL.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            THREAD_LOCAL.set(map);
        }
        return map.get(key);
    }

    public static void setClaims(Map<String, Object> claims) {
        setUserId(Long.valueOf(claims.get(TokenConstants.USER_ID_KEY).toString()));
        setUserTokenRedisKey((String) claims.get(TokenConstants.USER_TOKEN_REDIS_KEY));
    }

    public static Long getUserId() {
        Object userId = get(TokenConstants.USER_ID_KEY);
        return userId == null ? null : (Long) userId;
    }

    public static void setUserId(Long userId) {
        set(TokenConstants.USER_ID_KEY, userId);
    }

    public static String getUserTokenRedisKey() {
        Object value = get(TokenConstants.USER_TOKEN_REDIS_KEY);
        return value == null ? null : (String) value;
    }

    public static void setUserTokenRedisKey(String userTokenRedisKey) {
        set(TokenConstants.USER_TOKEN_REDIS_KEY, userTokenRedisKey);
    }

    public static String getTicket() {
        Object value = get(TokenConstants.TICKET);
        return value == null ? null : (String) value;
    }

    public static void setTicket(String ticket) {
        set(TokenConstants.TICKET, ticket);
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }
}
